package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * Stream 中文称为 “流”，通过将集合转换为这么一种叫做 “流” 的元素序列，
     * 通过声明性方式，能够对集合中的每个元素进行一系列并行或串行的流水线操作。
     */
    @Override
    public List<CategoryEntity> listWithTree() {

        List<CategoryEntity> selectList = this.baseMapper.selectList(null);

        // 1 查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        // 2 组装成父子的树形结构
        //   找到一级分类（level_1_Menus 即最高层级的分类集合，它们没有父类别）
        List<CategoryEntity> level_1_Menus = entities.stream().filter(categoryEntity -> {
            //找到父id为0的数据，并将其收集成一个集合
            return categoryEntity.getParentCid() == 0;
        }).map((menu) -> {
            //递归查询并设置它的子分类
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            //先进行了一个空值判断处理，再去排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level_1_Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 找到完整路径
     */
    @Override
    public Long[] findCateLogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        paths = findParentPath(catelogId, paths);
        // 收集的时候是顺序 前端是逆序显示的 所以用集合工具类给它逆序一下
        Collections.reverse(paths);
        return paths.toArray(new Long[paths.size()]);
    }

    /**
     * 级联更新所有关联的数据
     *
     * @Transactional 事务
     * @CacheEvict 缓存清除，更新之后就要删除旧缓存
     * @Caching 组合多个缓存相关的操作
     * allEntries 删除当前分区下的所有缓存
     */
    @CacheEvict(value = {"catagory"}, allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        //更新自己的表
        this.updateById(category);
        //级联更新其他的表
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    /**
     * @Cacheable：表示当前方法的结果需要缓存 value：缓存的命名空间
     * key：缓存的key
     * sync = true：加锁，解决缓存击穿
     */
    @Cacheable(value = {"catagory"}, key = "#root.method.name", sync = true)
    @Override
    public List<CategoryEntity> getLevel1Catagories() {
        log.info("getLevel1Catagories方法被调用...");
        List<CategoryEntity> categoryEntityList = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntityList;
    }

    /**
     * 查询三级分类，先查缓存，没有才查数据库
     */
    @Cacheable(value = {"catagory"}, key = "#root.method.name")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {

        System.out.println(Thread.currentThread().getName() + "查询了数据库");
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        List<CategoryEntity> category = getParent_cid(selectList, 0L);

        //2、封装数据
        Map<String, List<Catelog2Vo>> parent_cid = category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、查到这个一级分类下的所有二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());

            //2、封装上面的结果
            List<Catelog2Vo> catalog2Vos = new ArrayList<>();
            if (categoryEntities != null && categoryEntities.size() != 0) {
                catalog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catalog2Vo = new Catelog2Vo(
                            l2.getParentCid().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catalog = getParent_cid(selectList, l2.getCatId());
                    List<Catelog2Vo.Catelog3Vo> collectlevel3 = new ArrayList<>();
                    if (level3Catalog != null && !level3Catalog.isEmpty()) {
                        //2、封装成指定格式
                        collectlevel3 = level3Catalog.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catalog3Vo = new Catelog2Vo.Catelog3Vo(l3.getParentCid().toString(),
                                    l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                    }
                    catalog2Vo.setCatalog3List(collectlevel3);
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));

        return parent_cid;

    }


    /**
     * 使用Redisson实现分布式锁，从数据库查询查询三级分类
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDBWithRedissonLock() {
        //创建锁
        RLock lock = redissonClient.getLock("CatalogJson-lock");
        lock.lock();
        Map<String, List<Catelog2Vo>> dataFromDB = null;
        try {
            dataFromDB = getCatalogJsonFromDB();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return dataFromDB;
    }

    /**
     * 使用原始的redis实现分布式锁，从数据库查询查询三级分类
     *
     * @Deprecated：过时
     */
    @Deprecated
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDBWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        //1、占分布式锁
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 30, TimeUnit.SECONDS);
        if (lock) {
            log.info(Thread.currentThread().getName() + "获取分布式锁成功");
            Map<String, List<Catelog2Vo>> dataFromDB;
            try {
                //加锁后，尝试查询数据库
                dataFromDB = getCatalogJsonFromDB();
            } finally {
                //创建lua脚本
                String lua = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                        "then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                RedisScript<Long> luaScript = RedisScript.of(lua, Long.class);
                //删除锁，删除成功返回1，不成功返回0
                Long isDelete = stringRedisTemplate.execute(luaScript, Arrays.asList("lock"), uuid);
            }
            return dataFromDB;
        } else {
            log.info(Thread.currentThread().getName() + "获取分布式锁失败，等待重试");
            /***
             * 加锁失败，则先休眠一会儿，再以“自旋”的方式重试，即调用自己
             * */
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDBWithRedisLock();
        }
    }

    /**
     * 从数据库查询查询三级分类
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDB() {
        //得到锁以后应该再去缓存中确定一次，如果没有才需要继续查询
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            //缓存不为null,直接返回，
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }
        log.info(Thread.currentThread().getName() + "查询了数据库");
        //1、查出所有一级分类，
        List<CategoryEntity> category = getLevel1Catagories();
        //2、封装数据
        Map<String, List<Catelog2Vo>> parent_cid = category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、查到这个一级分类下的所有二级分类
            List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            //2、封装上面的结果
            List<Catelog2Vo> catelog2Vos = new ArrayList<>();
            if (categoryEntities != null && categoryEntities.size() != 0) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catalog2Vo = new Catelog2Vo(
                            l2.getParentCid().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catalog = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq(
                            "parent_cid", l2.getCatId()));
                    List<Catelog2Vo.Catelog3Vo> collectlevel3 = new ArrayList<>();
                    if (level3Catalog != null && !level3Catalog.isEmpty()) {
                        //2、封装成指定格式
                        collectlevel3 = level3Catalog.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catalog3Vo = new Catelog2Vo.Catelog3Vo(l3.getParentCid().toString(),
                                    l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                    }
                    catalog2Vo.setCatalog3List(collectlevel3);
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        //将查询到的数据放到redis上
        String s = JSON.toJSONString(parent_cid);
        stringRedisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);
        return parent_cid;
    }

    /**
     * 递归收集所有父节点
     */
    private List<Long> findParentPath(Long catlogId, List<Long> paths) {
        // 1、收集当前节点id
        paths.add(catlogId);
        CategoryEntity byId = this.getById(catlogId);
        //ParentCid不是0，就说明有父类，就继续递归搜索父节点
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 递归查找菜单的所有子菜单
     * CategoryEntity ： 类别实体
     * all ： 总类别，里面包含所有类别信息
     * root： 根类别，找根类别的子类
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            // 注意此处应该用longValue()来比较，否则会出先bug，因为parentCid和catId是long类型
            // 若当前类别（此处的categoryEntity是一个变量，表示某个类别）的ParentCid == 根类别的CatId，那就表明当前类别是root的子类别
            return categoryEntity.getParentCid().longValue() == root.getCatId().longValue();
        }).map(categoryEntity -> {
            // 1 找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            // 2 菜单的排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid().equals(parent_cid)).collect(Collectors.toList());
        return collect;
    }
}
